﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Text;
using QTMusic.BaseClasses;

namespace QTMusic.UserControls
{
    public partial class LoginPanel : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TbUsername.Attributes.Add("onfocus", "ToggleWatermark('TbUsername','');");
                TbUsername.Attributes.Add("onblur", "ToggleWatermark('TbUsername','username');");
                TbPassword.Attributes.Add("onfocus", "ToggleWatermark('TbPassword','');");
                TbPassword.Attributes.Add("onblur", "ToggleWatermark('TbPassword','password');");
                TbPassword.Text = "password";
            }
        }

        //cmd.Parameters.Add("@ProductID", SqlDbType.Int);
        //cmd.Parameters["@ProductID"].Value = Convert.ToInt32(Request["ProductID"]);
        protected void BtnLogin_Clicked(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(Common.connString);
            SqlCommand sql = new SqlCommand("SELECT * FROM [user] WHERE user_name=@usname AND user_password=@pass", conn);

            sql.Parameters.AddWithValue("@usname", TbUsername.Text);
            sql.Parameters.AddWithValue("@pass", TbPassword.Text);

            DataSet ds = new DataSet();
            SqlDataAdapter sda = new SqlDataAdapter(sql);
            sda.Fill(ds, "User");

            if (ds.Tables["User"].Rows.Count != 0)
            {
                HttpCookie cookie;
                if ((cookie = Request.Cookies["QTCookie"]) == null)
                    cookie = new HttpCookie("QTCookie");
                cookie["Name"] = TbUsername.Text;
                cookie["ID"] = ds.Tables["User"].Rows[0].Field<int>("user_id").ToString();
                cookie.Expires = DateTime.Now.AddYears(1);

                Response.Cookies.Add(cookie);
                Response.Redirect("~/Websites/Profile.aspx");
            }
            else
            {
                //redirect to re-login page
                Response.Redirect("~/Websites/Login.aspx");
            }
            conn.Close();
        }
    }
}